import http.client
import json
from comm.module import *
from comm.LogUtils import logger
from comm.postgresutility import postsql_utility

# 试剂危险分类列表查询
def doGetdangerList():
   try:
      logger.info('141:试剂危险分类列表查询')

      httpconn = http.client.HTTPSConnection(global_url)
      payload = ''
      headers = {
         'app-id': global_appid,
         'app-key': global_appkey
      }
      httpconn.request("GET", "/openapi/materiel/danger/list", payload, headers)
      res = httpconn.getresponse()
      data = res.read()
      data = data.decode("utf-8")
      # print(data.decode("utf-8"))
      #logger.info('141:' + data.decode("utf-8"))
      httpconn.close()

      json_str = json.loads(data)
      ierrCode = json_str["errCode"]
      if (ierrCode == 200):
         # 查询当前试剂危险分类
         sql = "select fclassstno from i_ts_good_class"
         sql = sql + " where fsite_no='" + global_site + "'"
         logger.info('141:' + sql)
         conn, cursor = postsql_utility.get_conn()
         data_2 = postsql_utility.select(sql=sql, cursor=cursor)
         sqllist = []

         # 遍历当前获取的数据
         for j1 in range(len(json_str["data"])):
            # print(json_str["data"][j1], end="\n")
            icat_exists = False
            icat_id = json_str["data"][j1]["id"]
            icat_code = json_str["data"][j1]["code"]
            icat_name = json_str["data"][j1]["name"]
            icat_flag = json_str["data"][j1]["isDanger"]  # 是否危险分类
            icat_value = 0
            if (icat_flag == True):
               icat_value = 1

            for j2 in range(len(data_2)):
               if (str(data_2[j2][0]) == str(icat_code)):
                  icat_exists = True
                  break

            if (icat_exists == False):
               sql = "insert into i_ts_good_class(fsite_no,fclassstno,fclassstname,fparentno"
               sql = sql + ",fclassstyle,flevel,feffday,fupddate,foperator)"
               sql = sql + "values('" + global_site + "','" + icat_code + "','" + icat_name + "',0"
               sql = sql + "," + str(icat_value) + ",1," + str(icat_id) + ",now(),58);"
               sqllist.append(sql)
      else:
         print(json_str["errMsg"])

      # 是否有新试剂分类资料
      if (len(sqllist) > 0):
         i = postsql_utility.executemuch(sqllist, cursor=cursor, connect=conn)

         if i != "OK":
            #print(f"失败: {i}")
            logger.info('141:失败' + str(i))
         else:
            #print(f"成功: {i}")
            logger.info('141:成功' + str(i))
      else:
         #print("没有试剂危险分类数据")
         logger.info('141:没有试剂危险分类数据' )

   except Exception as e:
      logger.info('141:错误'+str(e))

# 试剂配置查询，同步烨煊初始化的试剂基本资料
def doGetcasList():
   logger.info('142:试剂配置查询')

   # 查询试剂数据
   sql = " select fgoodno from i_ts_good_info"
   sql = sql + " where fsite_no='" + global_site + "'"
   logger.info('142:' + sql)
   conn, cursor = postsql_utility.get_conn()
   data_2 = postsql_utility.select(sql=sql, cursor=cursor)


   itotpage = 0
   ipageno = 1
   while (1 == 1):
      try:
         httpconn = http.client.HTTPSConnection(global_url)
         payload = ''
         headers = {
            'app-id': global_appid,
            'app-key': global_appkey
         }
         httpconn.request("GET", "/openapi/materiel/cas/list?pageSize=20&pageNo=" + str(ipageno), payload, headers)
         res = httpconn.getresponse()
         data = res.read()
         data = data.decode("utf-8")
         #print(data.decode("utf-8"))
         # logger.info('141:' + data.decode("utf-8"))
         httpconn.close()

         #遍历数据
         json_str = json.loads(data)
         ierrCode = json_str["errCode"]
         if (ierrCode == 200):
            ipage = int(json_str["totalItems"])
            itotpage = ipage // 20 + 1;
            if (ipageno >= itotpage):
               break
            else:
               ipageno = ipageno + 1

            print(str(json_str["totalItems"]) + ",当前页:" + str(ipageno) + ",总页数:" + str(itotpage), end="\n")
            sqllist = []

            # 遍历当前获取的数据
            for j1 in range(len(json_str["data"])):
               igood_exists = False
               igood_id = json_str["data"][j1]["id"]
               igood_code = json_str["data"][j1]["id"]
               igood_name = json_str["data"][j1]["productName"]
               igood_cas = json_str["data"][j1]["casCode"]
               igood_ename = json_str["data"][j1]["productNameEn"]
               igood_unit = json_str["data"][j1]["capacityUnit"]
               igood_date = json_str["data"][j1]["updatedTime"]

               #替换单引号
               igood_name = igood_name.replace("'","")
               igood_ename= igood_ename.replace("'","")

               #试剂分类
               icat_name =""
               igood_cat = json_str["data"][j1]["dangers"]
               for j2 in range(len(igood_cat)):
                  icat_name = icat_name + igood_cat[j2]["name"]+","

               for j2 in range(len(data_2)):
                  if (str(data_2[j2][0]) == str(igood_code)):
                     igood_exists = True
                     break

               if (igood_exists == False):
                  sql = "insert into i_ts_good_info(fsite_no,fgoodno,fgoodname,fcasno,fbarcode"
                  sql = sql + ",fengname,fclassstno,fspec,funit,feffday"
                  sql = sql + ",fpurity,fbuyprice,fstorageflag,fsafeqty,fheightqty,fsafecard "
                  sql = sql + ",fordunit,fordpack,fgoodstate,fupddate,foperator)"
                  sql = sql + "values('" + global_site + "','" + str(igood_code) + "','" + igood_name + "','" + igood_cas + "'," + str(igood_id)
                  sql = sql + ",'" + igood_ename + "',1,1,'" + igood_unit + "',0"
                  sql = sql + ",0,0,11,0,999,'"+icat_name+"'"
                  sql = sql + ",'" + igood_unit + "',1,1,'"+str(igood_date)+"',0);"
                  #print(sql)
                  sqllist.append(sql)

            # 是否有新试剂资料
            if (len(sqllist) > 0):
               i = postsql_utility.executemuch(sqllist, cursor=cursor, connect=conn)

               if i != "OK":
                  # print(f"失败: {i}")
                  logger.info('142:失败' + str(i))
               else:
                  # print(f"成功: {i}")
                  logger.info('142:成功' + str(i))
            else:
               # print("没有新试剂数据")
               logger.info('142:没有新试剂数据')

         else:
            print(json_str["errMsg"])

      except Exception as e:
         logger.info('142:错误' + str(e))
         break


# 新增或编辑试剂配置接口2
def doAddCas2(py_dict,igood_no):
    try:
       conn = http.client.HTTPSConnection(global_url)
       payload = json.dumps(py_dict)
       headers = {
          'app-id': global_appid,
          'app-key': global_appkey,
          'Content-Type': 'application/json'
       }
       conn.request("POST", "/openapi/materiel/cas/added", payload, headers)
       res = conn.getresponse()
       data = res.read()
       # print(data.decode("utf-8"))
       logger.info('143:' + data.decode("utf-8"))
       conn.close()

       json_str = json.loads(data)
       ierrCode = json_str["data"]["errCode"]
       if(ierrCode==200):
          #修改旗标
          sql="update i_ts_good_info"
          sql=sql +" set foperator=0"
          sql=sql +" where fsite_no='" + global_site + "'"
          sql=sql +" and fgoodno="+str(igood_no)
          conn, cursor = postsql_utility.get_conn()
          iOK = postsql_utility.execute(sql=sql, cursor=cursor)

    except Exception as e:
        logger.info('143:错误'+str(e))

#新增或修改试剂配置,标注那些是导入，那些是实验室系统新增
def doAddCas():
   try:
      logger.info('143:手工批量添加试剂')

      # 查询试剂数据
      # payload = json.dumps({
      #    "capacityUnit": "g",
      #    "attributes": [
      #       {
      #          "id": 18
      #       },
      #       {
      #          "id": 20
      #       }
      #    ],
      #    "productName": "这是一个新的试剂配置",
      #    "alias": "新配置",
      #    "productNameEn": "a new reagent cas",
      #    "aliasEn": "new cas",
      #    "casCode": "1-1-1-1",
      #    "dangerIds": [
      #       2
      #    ]
      # })
      sql = " select fbarcode,fgoodno,fgoodname,fcasno,fengname,funit"
      sql = sql +" from i_ts_good_info"
      sql = sql + " where fsite_no='" + global_site + "'"
      sql = sql + " and foperator>0"  #　>0　表示实验室系统新增的
      logger.info('142:' + sql)
      conn, cursor = postsql_utility.get_conn()
      data = postsql_utility.select(sql=sql, cursor=cursor)

      for j1 in range(len(data)):
          data_dict = {}
          data_dict["capacityUnit"] = int(data[j1][5])
          attr_list = []
          data_dict["attributes"] = attr_list
          danger_list = []
          data_dict["dangerIds"] = danger_list
          data_dict["productName"] = data[j1][2]
          data_dict["alias"] = "新配置"
          data_dict["productNameEn"] = data[j1][3]
          data_dict["aliasEn"] = ""
          data_dict["casCode"] = data[j1][4]
          #print(data_dict)
          doAddCas2(data_dict,data[j1][1])

   except Exception as e:
      logger.info('143:错误' + str(e))

#直接执行
#doGetcasList()